package com.wehealth.biz_ecg.helper;

import static com.wehealth.three.lib_connect.utils.EcgFileUtil.saveEcgDataToXMLFile;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;

import com.wehealth.ecg.jni.analyse.EcgAnalyse;
import com.wehealth.three.lib_connect.constant.CommonKeyConstant;
import com.wehealth.three.lib_connect.utils.AppGlobals;
import com.wehealth.three.lib_connect.utils.ECGDataAutoAnalyseUtils;
import com.wehealth.biz_ecg.utils.PDFUtils;
import com.wehealth.three.lib_connect.utils.StringUtils;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;

@SuppressLint("SdCardPath")
public class SaveFileManualThread extends Thread {
    private final int SAVE_FILE_TYPE_XML = 1;
    private final int SAVE_FILE_TYPE_PDF = 2;

    private final int SAVE_PDF_XML_FILE_SUCCESS = 897;
    public boolean saveFileThreadFLAG;
    private EcgAnalyse ecgAnalyse;
    private Handler handler;
    private Context context;
    public LinkedList<Map<String, Object>> queue = new LinkedList<>();
    PDFUtils pdfUtils;
    private String xmlFilePath;
    private boolean saveFileState = false;

    public SaveFileManualThread(Context mContext, Handler mHandler) {
        ecgAnalyse = new EcgAnalyse();
        ecgAnalyse.Axis = new int[3];
        ecgAnalyse.ecgResult = new int[12];
        context = mContext;
        handler = mHandler;
        saveFileThreadFLAG = true;
        pdfUtils = new PDFUtils();
    }

    public void addToQueue(Map<String, Object> map) {
        synchronized (queue) {
            queue.add(map);
        }
    }

    @Override
    public void run() {
        super.run();
        while (saveFileThreadFLAG) {
            try {
                if (queue.isEmpty() && !saveFileState) {
                    sleep(1000);
                } else if (queue.size() > 0) {
                    synchronized (queue) {
//						long start = System.currentTimeMillis();
                        Map<String, Object> map = queue.removeFirst();
                        long ecg2DeviceData_time = (Long) map.get("ecg2DeviceData_time");
                        int saveFileManualCount = (Integer) map.get("saveFileManualCount");
                        int timeSecondCount = (Integer) map.get("timeSecondCount");
                        Map<Integer, Integer[]> dataMap = StringUtils.praseIntegerData(map);
                        if (saveFileManualCount == 0 && timeSecondCount < 20) {
                            saveManualData(SAVE_FILE_TYPE_PDF, map, dataMap);
                        } else {
                            saveManualData(SAVE_FILE_TYPE_XML, map, dataMap);
                        }

                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (saveFileState) {
                saveFileThreadFLAG = false;
            }
        }
    }


    public void saveManualData(int type, Map<String, Object> map, Map<Integer, Integer[]> dataMap) {
        String Gain = (String) map.get("Gain");
        String Speed = (String) map.get("Speed");
        String FilterBase = (String) map.get("FilterBase");
        String FilterMC = (String) map.get("FilterMC");
        String FilterAC = (String) map.get("FilterAC");
        String FilterLP = (String) map.get("FilterLP");
        String HeartRate = (String) map.get("HeartRate");
        String patId = (String) map.get("PAT_ID");
        int patAge = (Integer) map.get("PAT_AGE");
        int patGender = (Integer) map.get("PAT_GENDER");
        String patName = (String) map.get("PAT_NAME");
        int waveGain = (Integer) map.get("waveGain");
        int waveSpeed = (Integer) map.get("waveSpeed");
        int waveSingleDisplay_Switch = (Integer) map.get("waveSingleDisplay_Switch");
        Map<String, Map<String, String>> listMaps = new HashMap<>();
        Map<String, String> pInfo = new HashMap<>();
        Map<String, String> analyses = new HashMap<>();
        int[] ecgAnas = StringUtils.getMapEcgDataINTs(map);
        int dataLen = dataMap.get(0).length;
        //自动分析结论
        ecgAnalyse.initEcgAnalyseLib(3495.2533333f * 3);
        int[] paceBuffer = new int[dataLen];
        ecgAnalyse.analyseEcgData(ecgAnalyse, ecgAnas, dataLen, 12, paceBuffer, 0, 0);
        Log.e("TAG", "分析完毕");
        int[] axis = ecgAnalyse.Axis;
        int[] resultCode = ecgAnalyse.ecgResult;
        Set<String> ECGResult = ECGDataAutoAnalyseUtils.getAnalyseResult(resultCode);
        int hr = ecgAnalyse.HR;
        int pr = ecgAnalyse.PR;
        int qrs = ecgAnalyse.QRS;
        int qt = ecgAnalyse.QT;
        int qtc = ecgAnalyse.QTc;
        int rr = ecgAnalyse.RR;
        int rv5 = ecgAnalyse.RV5;
        int sv1 = ecgAnalyse.SV1;
        if (TextUtils.isEmpty(HeartRate)) {
            analyses.put("HeartRate", String.valueOf(hr));
        } else {
            analyses.put("HeartRate", HeartRate);
        }
        Log.e("TAG", "心率值：" + HeartRate + "  分析值：" + hr);
        analyses.put("PRInterval", String.valueOf(pr));
        analyses.put("RRInterval", String.valueOf(rr));
        analyses.put("QRSDuration", String.valueOf(qrs));
        analyses.put("QTD", String.valueOf(qt));
        analyses.put("QTC", String.valueOf(qtc));
        analyses.put("RV5", String.valueOf(rv5));
        analyses.put("SV1", String.valueOf(sv1));
        analyses.put("RV5SV1", String.valueOf((Math.abs(rv5) + Math.abs(sv1))));
        analyses.put("PAxis", String.valueOf(axis[0]));
        analyses.put("QRSAxis", String.valueOf(axis[1]));
        analyses.put("TAxis", String.valueOf(axis[2]));
        String Auto_Result = "";
        for (String str : ECGResult) {
            Auto_Result = Auto_Result + " " + str;
        }
        analyses.put("Auto_Result", Auto_Result);
        analyses.put("Gain", Gain);
        analyses.put("Speed", Speed);
        analyses.put("FilterBase", FilterBase);
        analyses.put("FilterMC", FilterMC);
        analyses.put("FilterAC", FilterAC);
        analyses.put("FilterLP", FilterLP);
        pInfo.put("Name", patName);
        pInfo.put("ID", patId);
        pInfo.put("Gender", String.valueOf(patGender));
        pInfo.put("AGE", String.valueOf(patAge));
        pInfo.put("ecg_checktime", String.valueOf(System.currentTimeMillis()));
        listMaps.put(CommonKeyConstant.ECG_PATIENT_INFO, pInfo);
        listMaps.put(CommonKeyConstant.ECG_ANALYSE_PARAM, analyses);
        Map<String, String> xmlDataMap = StringUtils.parseMapDataToString(map);
        if (type == SAVE_FILE_TYPE_XML) {
            saveEcgDataToXMLFile(AppGlobals.INSTANCE.get(), listMaps, xmlDataMap);
        } else {
            pdfUtils.savePDFIntegers(context, listMaps, dataMap, waveGain, waveSpeed, waveSingleDisplay_Switch);

        }
        handler.sendEmptyMessage(SAVE_PDF_XML_FILE_SUCCESS);
        Log.e("TAG", "xml over");
    }

    /**
     * 设置为false，表示线程不再sleep
     *
     * @param b
     */
    public void setThreadSleepState(boolean b) {
        saveFileState = b;
    }

    /***
     * 设置为false，线程循环标识为false
     * @param flag
     */
    public void setThreadFlag(boolean flag) {
        saveFileThreadFLAG = flag;
    }

}
